/**
 * 数据同步服务
 * 处理本地数据与服务器数据的同步
 */

import { LocalStorageManager, type SyncSettings } from '@/utils/localStorage'
import { useEventsStore } from '@/stores/events'
import { api } from '@/api/request'
import type { Event, EventType, DietType } from '@/types'

export interface SyncResult {
  success: boolean
  message: string
  syncedItems: {
    events: number
    eventTypes: number
    dietTypes: number
  }
  errors?: string[]
}

/**
 * 数据同步服务类
 */
export class SyncService {
  private static syncTimer: number | null = null
  private static isSyncing = false
  private static useBackendSync = false // 是否使用后端同步，默认false使用本地存储

  /**
   * 配置同步模式
   */
  static setBackendSyncMode(enabled: boolean): void {
    this.useBackendSync = enabled
    console.log(`同步模式已切换为: ${enabled ? '后端同步' : '本地存储'}`)
  }

  /**
   * 获取当前同步模式
   */
  static isBackendSyncEnabled(): boolean {
    return this.useBackendSync
  }

  /**
   * 手动同步数据
   */
  static async manualSync(): Promise<SyncResult> {
    if (this.isSyncing) {
      return {
        success: false,
        message: '同步正在进行中，请稍后再试',
        syncedItems: { events: 0, eventTypes: 0, dietTypes: 0 }
      }
    }

    try {
      this.isSyncing = true
      return await this.performSync()
    } finally {
      this.isSyncing = false
    }
  }

  /**
   * 启动自动同步
   */
  static startAutoSync(): void {
    const settings = LocalStorageManager.getSyncSettings()
    
    if (!settings.autoSync) {
      this.stopAutoSync()
      return
    }

    // 清除现有定时器
    this.stopAutoSync()

    // 设置新的定时器
    const intervalMs = settings.syncInterval * 60 * 1000 // 转换为毫秒
    this.syncTimer = window.setInterval(async () => {
      if (!this.isSyncing) {
        try {
          await this.performSync()
        } catch (error) {
          console.error('自动同步失败:', error)
        }
      }
    }, intervalMs)

    console.log(`自动同步已启动，间隔: ${settings.syncInterval} 分钟`)
  }

  /**
   * 停止自动同步
   */
  static stopAutoSync(): void {
    if (this.syncTimer) {
      clearInterval(this.syncTimer)
      this.syncTimer = null
      console.log('自动同步已停止')
    }
  }

  /**
   * 执行同步操作
   */
  private static async performSync(): Promise<SyncResult> {
    const errors: string[] = []
    let syncedItems = { events: 0, eventTypes: 0, dietTypes: 0 }

    try {
      const eventsStore = useEventsStore()

      if (this.useBackendSync) {
        // 后端同步模式
        syncedItems = await this.performBackendSync(eventsStore, errors)
      } else {
        // 本地存储同步模式
        syncedItems = await this.performLocalSync(eventsStore, errors)
      }
    } catch (error) {
      errors.push(`同步过程中发生错误: ${error}`)
    }

    // 更新最后同步时间
    LocalStorageManager.updateLastSyncTime()

    return {
      success: errors.length === 0,
      message: errors.length === 0 ? '同步成功' : `同步完成，但有 ${errors.length} 个错误`,
      errors,
      syncedItems
    }
  }

  /**
   * 执行本地存储同步
   */
  private static async performLocalSync(eventsStore: any, errors: string[]): Promise<{ events: number, eventTypes: number, dietTypes: number }> {
    let syncedItems = { events: 0, eventTypes: 0, dietTypes: 0 }

    // 同步事件数据
    try {
      const localEvents = LocalStorageManager.getEvents()
      const storeEvents = eventsStore.events as Event[]

      // 简单的同步策略：以store中的数据为准，保存到本地
      if (JSON.stringify(localEvents) !== JSON.stringify(storeEvents)) {
        LocalStorageManager.saveEvents(storeEvents)
        syncedItems.events = storeEvents.length
      }
    } catch (error) {
      errors.push(`事件同步失败: ${error}`)
    }

    // 同步事件类型数据
    try {
      const localEventTypes = LocalStorageManager.getEventTypes()
      const storeEventTypes = eventsStore.eventTypes as EventType[]

      if (JSON.stringify(localEventTypes) !== JSON.stringify(storeEventTypes)) {
        LocalStorageManager.saveEventTypes(storeEventTypes)
        syncedItems.eventTypes = storeEventTypes.length
      }
    } catch (error) {
      errors.push(`事件类型同步失败: ${error}`)
    }

    // 同步饮食类型数据
    try {
      const localDietTypes = LocalStorageManager.getDietTypes()
      const storeDietTypes = eventsStore.dietTypes as DietType[]

      if (JSON.stringify(localDietTypes) !== JSON.stringify(storeDietTypes)) {
        LocalStorageManager.saveDietTypes(storeDietTypes)
        syncedItems.dietTypes = storeDietTypes.length
      }
    } catch (error) {
      errors.push(`饮食类型同步失败: ${error}`)
    }

    return syncedItems
  }

  /**
   * 执行后端同步（预留接口）
   */
  private static async performBackendSync(eventsStore: any, errors: string[]): Promise<{ events: number, eventTypes: number, dietTypes: number }> {
    let syncedItems = { events: 0, eventTypes: 0, dietTypes: 0 }

    try {
      // 同步事件数据到后端
      const storeEvents = eventsStore.events as Event[]
      const response = await api.post('/sync/events', { events: storeEvents })

      if (response.success) {
        syncedItems.events = storeEvents.length
        console.log('事件数据已同步到后端')
      } else {
        errors.push('后端事件同步失败')
      }
    } catch (error) {
      errors.push(`后端事件同步失败: ${error}`)
      console.error('后端同步失败，回退到本地存储模式')

      // 回退到本地存储
      return await this.performLocalSync(eventsStore, errors)
    }

    try {
      // 同步事件类型数据到后端
      const storeEventTypes = eventsStore.eventTypes as EventType[]
      const response = await api.post('/sync/event-types', { eventTypes: storeEventTypes })

      if (response.success) {
        syncedItems.eventTypes = storeEventTypes.length
        console.log('事件类型数据已同步到后端')
      } else {
        errors.push('后端事件类型同步失败')
      }
    } catch (error) {
      errors.push(`后端事件类型同步失败: ${error}`)
    }

    try {
      // 同步饮食类型数据到后端
      const storeDietTypes = eventsStore.dietTypes as DietType[]
      const response = await api.post('/sync/diet-types', { dietTypes: storeDietTypes })

      if (response.success) {
        syncedItems.dietTypes = storeDietTypes.length
        console.log('饮食类型数据已同步到后端')
      } else {
        errors.push('后端饮食类型同步失败')
      }
    } catch (error) {
      errors.push(`后端饮食类型同步失败: ${error}`)
    }

    return syncedItems
  }

  /**
   * 从本地存储恢复数据到store
   */
  static async restoreFromLocal(): Promise<SyncResult> {
    const errors: string[] = []
    let syncedItems = { events: 0, eventTypes: 0, dietTypes: 0 }

    try {
      // const eventsStore = useEventsStore()
      const localData = LocalStorageManager.getAllData()

      // 恢复事件数据
      if (localData.events.length > 0) {
        try {
          // 这里需要实现将本地数据恢复到store的逻辑
          // 由于当前store使用mock数据，这里只是示例
          syncedItems.events = localData.events.length
        } catch (error) {
          errors.push(`恢复事件数据失败: ${error}`)
        }
      }

      // 恢复事件类型数据
      if (localData.eventTypes.length > 0) {
        try {
          syncedItems.eventTypes = localData.eventTypes.length
        } catch (error) {
          errors.push(`恢复事件类型数据失败: ${error}`)
        }
      }

      // 恢复饮食类型数据
      if (localData.dietTypes.length > 0) {
        try {
          syncedItems.dietTypes = localData.dietTypes.length
        } catch (error) {
          errors.push(`恢复饮食类型数据失败: ${error}`)
        }
      }

      const hasErrors = errors.length > 0
      return {
        success: !hasErrors,
        message: hasErrors 
          ? `恢复完成，但有 ${errors.length} 个错误` 
          : '从本地存储恢复数据成功',
        syncedItems,
        errors: hasErrors ? errors : undefined
      }

    } catch (error) {
      return {
        success: false,
        message: `恢复数据失败: ${error}`,
        syncedItems: { events: 0, eventTypes: 0, dietTypes: 0 },
        errors: [String(error)]
      }
    }
  }

  /**
   * 更新同步设置
   */
  static updateSyncSettings(settings: SyncSettings): void {
    LocalStorageManager.saveSyncSettings(settings)
    
    // 重新启动自动同步（如果启用）
    if (settings.autoSync) {
      this.startAutoSync()
    } else {
      this.stopAutoSync()
    }
  }

  /**
   * 获取同步状态信息
   */
  static getSyncStatus(): {
    isAutoSyncEnabled: boolean
    lastSyncTime: string | null
    isSyncing: boolean
    syncInterval: number
  } {
    const settings = LocalStorageManager.getSyncSettings()
    return {
      isAutoSyncEnabled: settings.autoSync,
      lastSyncTime: LocalStorageManager.getLastSyncTime(),
      isSyncing: this.isSyncing,
      syncInterval: settings.syncInterval
    }
  }

  /**
   * 检查是否需要同步
   */
  static needsSync(): boolean {
    const lastSyncTime = LocalStorageManager.getLastSyncTime()
    if (!lastSyncTime) return true

    const settings = LocalStorageManager.getSyncSettings()
    const lastSync = new Date(lastSyncTime)
    const now = new Date()
    const diffMinutes = (now.getTime() - lastSync.getTime()) / (1000 * 60)

    return diffMinutes >= settings.syncInterval
  }

  /**
   * 清理同步服务
   */
  static cleanup(): void {
    this.stopAutoSync()
    this.isSyncing = false
  }
}

// 在应用启动时初始化同步服务
export function initSyncService(): void {
  // 检查本地存储是否可用
  if (!LocalStorageManager.isStorageAvailable()) {
    console.warn('本地存储不可用，同步功能将被禁用')
    return
  }

  // 启动自动同步（如果启用）
  const settings = LocalStorageManager.getSyncSettings()
  if (settings.autoSync) {
    SyncService.startAutoSync()
  }

  // 监听页面卸载事件，清理资源
  window.addEventListener('beforeunload', () => {
    SyncService.cleanup()
  })
}
